<template>
	<div class="login">
		<!-- {{password}}
		{{name}} -->
		<el-form
			ref="ruleFormRef"
			:model="ruleForm"
			status-icon
			:rules="rules"
			label-width="70px"
			class="demo-ruleForm"
		>
			<el-form-item label="User" prop="user">
				<el-input v-model.number="ruleForm.user" />
			</el-form-item>
			<el-form-item label="Password" prop="pass">
				<el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitForm(ruleFormRef)"
					>Login</el-button
				>
				<el-button @click="resetForm(ruleFormRef)">Reset</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import { reactive, ref } from 'vue'
import { FormInstance } from 'element-plus'
import { useRouter } from "vue-router";

export default {
	name: 'loginN',
	props: {
		msg: String
	},
	setup () {
		const $router = useRouter();
		const password = ref("124")
		const name = ref("root")
		const ruleFormRef = ref(FormInstance)
		const ruleForm = reactive({
			pass: '',
			user: ''
		})

		const validatePass = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('Please input the password'))
			} else {
				callback()
			}
		}

		const validateUser = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('Please input the user '))
			} else {
				callback()
			}
		}

		const rules = reactive({
			pass: [{ validator: validatePass, trigger: 'blur' }],
			user: [{ validator: validateUser, trigger: 'blur' }],
		})

		const submitForm = (formEl) => {
			if (!formEl) return
			formEl.validate((valid) => {
				if (valid) {
					localStorage.setItem("users", JSON.stringify({
						user: ruleForm.user,
						p: ruleForm.pass,
					}))
					$router.push({
						path: "/"
					});
				} else {
					console.log('error submit!')
					return false
				}
			})
		}

		const resetForm = (formEl) => {
			if (!formEl) return
			formEl.resetFields()
		}

		return {
			password,
			name,
			rules,
			submitForm,
			resetForm,
			ruleFormRef,
			ruleForm
		}
	}
}
</script>

<style scoped>
.login{
	width: 370px;
	height: 230px;
	padding: 40px 16px 0 16px;
	box-sizing: border-box;
	margin: 30px auto auto;
	border: 1px solid #e9e9e9;

}
</style>
